////////////////////////////
//
//
#include "stdafx.h"

#include "AsyncWorker.h"


CAsyncWorker::CAsyncWorker()
{
	m_nTaskId = 99;
}

CAsyncWorker::~CAsyncWorker()
{
}

CAsyncWorker& CAsyncWorker::Instance()
{
	static CAsyncWorker taskQueue;
	return taskQueue;
}

void CAsyncWorker::HandleMessage(ULONGLONG nTaskId, ULONGLONG wParam, ULONGLONG lParam)
{	
	ULONGLONG taskId = nTaskId;
	IAsyncTask* task = (IAsyncTask*)wParam;
	IAsyncTaskCallback* callback = (IAsyncTaskCallback*)lParam;

	if(task)
	{
		bool result = false;

		result = task->DoWork();
		if(callback)
		{
			try
			{
				callback->OnTaskComplete(taskId, result, task);
			}
			catch(...)
			{
				
			}
		}

		if (task)
		{
			delete task;
			task = NULL;
		}
	}
}

ULONGLONG CAsyncWorker::AddTask(IAsyncTask* task, IAsyncTaskCallback* callback)
{
	CLock lock(m_cs);

	m_nTaskId++;
	
	AddQueueMessage(m_nTaskId, (ULONGLONG)task, (ULONGLONG)callback);
	
	return m_nTaskId;
}

void CAsyncWorker::ClearJobs()
{
	ClearQueue();
}

int CAsyncWorker::GetJobCounts()
{
	return GetQueueSize();
}